package model

import (
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"strings"
	"sync"
	"yunzhan/api-server/internal/types"
	"yunzhan/common/models"
	agent "yunzhan/rpc-server/pb"
)

/**
 * @Author: way lee
 * @Date: 2024/10/10 13:49
 * @Desc:
 */

func RecordNodeResult(node *agent.NodeInfo, err error, nodes *[]string, nodeResults *[]*models.NodeResult, mu *sync.Mutex) {
	mu.Lock()
	defer mu.Unlock()
	if err != nil {
		logx.Errorf("节点 %s 部署失败: %v", node.Host, err)
		*nodes = append(*nodes, node.Host)
		*nodeResults = append(*nodeResults, &models.NodeResult{
			Node:  node,
			Error: err,
		})
	} else {
		logx.Infof("节点 %s 部署成功", node.Host)
		*nodes = append(*nodes, node.Host)
		*nodeResults = append(*nodeResults, &models.NodeResult{
			Node:  node,
			Error: nil,
		})
	}
}

func GenerateResponse(successNodes, failedNodes []string, nodeResults []*models.NodeResult) *types.DeployResponse {
	var data []string
	for _, result := range nodeResults {
		data = append(data, result.Node.Host)
	}
	resp := &types.DeployResponse{
		Code:    200,
		Message: "组件部署已开始",
		Data:    data,
	}

	if len(failedNodes) > 0 {
		resp.Code = 500
		resp.Message = fmt.Sprintf("部分节点执行部署失败. 成功节点: %s; 失败节点: %s", strings.Join(successNodes, ","), strings.Join(failedNodes, ","))
	} else {
		resp.Message = fmt.Sprintf("所有节点执行部署成功. 成功节点: %s", strings.Join(successNodes, ","))
	}

	return resp
}
